<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>房屋管理</title>
    <script src="../js/vue3.js"></script>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <!--    <script src="js/axios-interceptor.js"></script>-->
    <link rel="stylesheet" href="../css/index.css"/>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: "Helvetica Neue", Arial, sans-serif;
            background: #f4f6f9;
        }

        .search-container {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            align-items: center;
        }

        .search-container .el-form-item {
            margin: 0;
        }

        .table-container {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .pagination-container {
            margin-top: 15px;
            display: flex;
            justify-content: flex-end;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 搜索区域 -->
    <el-form :inline="true" class="search-container">
        <el-form-item label="房屋编号">
            <el-input v-model="searchForm.houseNo" placeholder="请输入房屋编号" clearable></el-input>
        </el-form-item>

        <el-form-item label="入住时间">
            <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    start-placeholder="start"
                    end-placeholder="end"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>

        <el-form-item label="房屋状态">
            <el-select style="width: 100px" v-model="searchForm.state" placeholder="请选择状态" clearable>
                <el-option v-for="s in state" :label="s.stateName" :value="s.stateId"></el-option>

            </el-select>
        </el-form-item>

        <el-form-item label="业主">
            <el-select style="width: 100px" v-model="searchForm.ownerId" placeholder="请选择业主" clearable>
                <el-option v-for="o in owners" :label="o.name" :value="o.id"></el-option>

            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleAdd">新增房屋</el-button>
            <el-button type="warning" @click="handleExport">导出Excel</el-button>
        </el-form-item>
    </el-form>

    <!-- 表格 -->
    <div class="table-container">
        <el-table :data="tableData" border stripe style="width: 100%">
            <el-table-column prop="hid" label="编号" width="80"></el-table-column>
            <el-table-column prop="houseNo" label="房号" width="100"></el-table-column>
            <el-table-column prop="floor" label="楼层" width="80"></el-table-column>
            <el-table-column prop="area" label="面积(㎡)" width="100"></el-table-column>
            <el-table-column prop="liveTime" label="入住时间" width="150" :formatter="formatTime"></el-table-column>
            <el-table-column prop="state" label="房间状态" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.state==1" class="ml-2" type="success">已入住</el-tag>
                    <el-tag v-if="scope.row.state==0" class="ml-2" type="error">未入住</el-tag>
                    <el-tag v-if="scope.row.state==2" class="ml-2" type="success">已出租</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="buildings.buildingName" label="楼名" width="120"></el-table-column>
            <el-table-column prop="buildings.location" label="单元" width="80"></el-table-column>
            <el-table-column prop="owners.name" label="姓名" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.owners===null" class="ml-2" type="success">空置</el-tag>
                    <el-tag v-else class="ml-2" type="error">{{scope.row.owners.name}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="owner.telphone" label="电话" width="150">
                <template #default="scope">
                    <el-tag v-if="scope.row.owners===null" class="ml-2" type="success">无</el-tag>
                    <el-tag v-else class="ml-2" type="error">{{scope.row.owners.telphone}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注"></el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div>
            <!-- 弹窗组件 -->
            <el-dialog
                    v-model="dialogVisible"
                    title="新增/修改信息"
                    width="700px"
                    :before-close="handleClose"
            >
                <el-form
                        :model="houseForm"
                        ref="formRef"
                        :rules="rules"
                        label-width="100px"
                        label-position="right"
                        class="house-form"
                >
                    <el-form-item label="房号" prop="houseNo">
                        <el-input v-model="houseForm.houseNo" placeholder="请输入房号"></el-input>
                    </el-form-item>

                    <el-form-item label="楼层" prop="floor">
                        <el-input-number v-model="houseForm.floor" :min="1" :max="50"
                                         controls-position="right"></el-input-number>
                    </el-form-item>

                    <el-form-item label="面积(㎡)" prop="area">
                        <el-input-number v-model="houseForm.area" :min="20" :max="500" :precision="2" :step="0.5"
                                         controls-position="right"></el-input-number>
                    </el-form-item>

                    <el-form-item label="入住时间" prop="liveTime">
                        <el-date-picker
                                v-model="houseForm.liveTime"
                                type="date"
                                placeholder="选择入住日期"
                                value-format="YYYY-MM-DD"
                        ></el-date-picker>
                    </el-form-item>

                    <el-form-item label="房间状态" prop="state">
                        <el-select v-model="houseForm.state" placeholder="请选择房间状态">
                            <el-option v-for="s in state" :label="s.stateName" :value="s.stateId"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="所属楼" prop="buildingId">
                        <el-select v-model="houseForm.buildingId" placeholder="请选择所属楼">
                            <el-option v-for="b in building" :label="b.buildingName" :value="b.buildingId"></el-option>

                        </el-select>
                    </el-form-item>

                    <el-form-item label="备注" prop="remarks" class="full-width">
                        <el-input
                                v-model="houseForm.remarks"
                                type="textarea"
                                :rows="3"
                                placeholder="请输入备注信息"
                        ></el-input>
                    </el-form-item>

                    <div class="form-footer full-width">
                        <el-button @click="cancel">取消</el-button>
                        <el-button type="primary" @click="submitForm">提交</el-button>
                    </div>
                </el-form>
            </el-dialog>

        </div>
        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    v-model:page-size="pageSize"
                    v-model:current-page="currentPage"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"></el-pagination>
        </div>
    </div>
</div>

<script>
    const {createApp, ref, reactive, onMounted, onUpdated} = Vue;
    const {ElMessage, ElMessageBox} = ElementPlus;
    const app = createApp({

        setup() {
            const searchForm = ref({});
            const dateRange = ref([]);
            const tableData = ref([]);
            const dialogVisible = ref(false);
            const total = ref(1);
            const pageSize = ref(5);
            const currentPage = ref(1);
            const title = ref("新增信息")
            const houseForm = ref({});
            const formRef = ref(null);
            const rules = ({
                houseNo: [
                    {required: true, message: '请输入房号', trigger: 'blur'},

                ],
                floor: [
                    {
                        required: true, message: '请输入楼层', trigger: 'blur',
                    },
                ],
                liveTime: [
                    {required: true, message: '请输入入住时间', trigger: 'blur'},
                ],
                state: [
                    {required: true, message: '请输入状态', trigger: 'blur'},
                ],
            })
            const handleSearch = () => {
                searchForm.value.start = dateRange.value[0];
                searchForm.value.end = dateRange.value[1];
                getHouse();
            };

            const handleReset = () => {
                searchForm.houseNo = '';
                searchForm.dateRange = [];
                searchForm.status = '';
                searchForm.owner = '';
            };
            //导出excl
            const handleExport = () => {
                window.location.href= "/house/download";
            };
            //新增
            const handleAdd = () => {
                dialogVisible.value = true;
            };
            //提交

            const submitForm = () => {

                if (formRef.value.validate((valid)=> {
                    if (valid) {
                        if (houseForm.value.hid==undefined && houseForm.value.hid== null) {
                            // 修改路线
                            updateHouse();
                            console.log(houseForm.value.hid)
                        } else {
                            // 新增路线
                            axios.post("/house", houseForm.value).then(resp => {
                                if (resp.data.code === 200) {
                                    console.log(resp.data)
                                    data(resp.data.msg);
                                }
                            }).catch(error => {
                                ElMessage.error(error.response.data.msg);
                            })
                        }
                    }
                })) ;
            }

            const data = (msg) => {
                ElMessage.success(msg);
                getHouse();
                houseForm.value = {}
                dialogVisible.value = false
            }
            //编辑
            const handleEdit = (row) => {
                axios.get(`/house/getHouseById/${row.hid}`)
                    .then(resp => {
                        houseForm.value = resp.data.data;
                        dialogVisible.value = true; // 显示弹窗
                        title.value = ref("修改信息")
                    })
                    .catch(error => {
                        ElMessage.error(error.response.data.msg);
                    })
            };
            //修改
            const updateHouse = () => {
                axios.put("/house/updateHouse", houseForm.value).then(resp => {
                    // 判断resp.data 是否大于1，如果大于1 则修改成功，刷新页面，关闭弹窗
                    if (resp.data.code === 200) {
                        data(resp.data.msg);
                    } else {
                        ElMessage.error(error.response.data.msg)
                    }
                })
            }


            //删除
            const handleDelete = (row) => {
                ElMessageBox.confirm(`确定要删除用户吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',

                }).then(() => {
                    // let mid = row.buildingId;
                    axios.delete(`/house/deleteById/${row.hid}`).then(resp => {
                        if (resp.data.code === 200) {
                            ElMessage.success(resp.data.msg);
                            getHouse();
                        } else {
                            alert("删除失败")
                        }
                    }).catch(error => {
                        ElMessage.error(error.response.data.msg);
                    })
                })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消删除',
                        })
                    })
            };
            //分页组件
            const handleSizeChange = (val) => {
                pageSize.value = val;
                getHouse();
            };

            const handlePageChange = (val) => {
                currentPage.value = val;
                getHouse();
            };

            //下拉组件
            const owners = ref([])
            const initSelect = () => {
                axios.get("/owner/getOwnerNameAndId").then(resp => {
                    owners.value = resp.data.data;
                })
            }
            const state = ref([])
            const initState = () => {
                axios.get("/house/getState").then(resp => {
                    state.value = resp.data.data;
                })
            }
            const building = ref([])
            const initBuilding = () => {
                axios.get("/build/getBuildingNameAndId").then(resp => {
                    building.value = resp.data.data;
                })
            }
            onMounted(() => {
                getHouse();
                initSelect();
                initState();
                initBuilding();
            });

            //得到数据
            const getHouse = () => {
                axios.post(`/house/${currentPage.value}/${pageSize.value}`, searchForm.value).then(resp => {
                    //将返回回来的集合数据赋值给表格绑定的数据源变量
                    //   resp.data   Result(obj:自己的集合数据)
                    console.log(resp.data)
                    tableData.value = resp.data.data.list;
                    total.value = resp.data.data.total;
                }).catch(error => {
                    console.log(error);
                    console.log("网络繁忙，请稍后再试")
                })

            }
            //格式化时间
            const formatTime = (row, column, cellValue, index) => {
                let d = new Date(cellValue);
                return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
            }
            //清楚验证红色字体
            const clearValid = () => {
                if (formRef && formRef.value) {
                    formRef.value.resetFields();
                }
            }
            const cancel = () => {
                clearValid();
                dialogVisible.value = false
            };
            return {
                building,
                initBuilding,
                cancel,
                dateRange,
                state,
                initState,
                searchForm,
                tableData,
                total,
                pageSize,
                currentPage,
                handleSearch,
                handleReset,
                handleAdd,
                handleExport,
                handleEdit,
                handleDelete,
                handleSizeChange,
                handlePageChange,
                getHouse,
                formatTime,
                dialogVisible,
                title,
                houseForm,
                rules,
                formRef,
                initSelect,
                owners,
                submitForm,
                updateHouse,
            };
        }
    });
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });
    // 注册 Element Plus 图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }
    app.mount("#app");
</script>
</body>
</html>